package com.rongzhe.house.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.rongzhe.house.common.SpringUtil;
import com.rongzhe.house.common.constants.Constants;
import com.rongzhe.house.common.constants.Parameters;
import com.rongzhe.house.common.resp.ApiResult;
import com.rongzhe.house.contract.entity.SysVersion;
import com.rongzhe.house.sys.service.SysService;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by JackWangon[www.coder520.com] 20:22 2018/5/2.
 */


public class VersionInterceptor implements HandlerInterceptor {


    private Parameters parameters = SpringUtil.getBean(Parameters.class);

    private AntPathMatcher matcher = new AntPathMatcher();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {


        if (isNoneVersion(request.getRequestURI().substring(4, request.getRequestURI().length()))) {
            //不需要判断版本的
            return true;
        }

        //先检测版本
        String version = request.getHeader(Constants.REQUEST_VERSION_KEY);
        //动态获取version参数 比较 如果要求的最低版本号大于传入的版本号  设置错误头
        SysVersion sysVersion = SpringUtil.getBean(SysService.class).version("all",version).getData();


        if (null==sysVersion) {
            //版本不匹配
            request.setAttribute("header-error", 400);
            request.setAttribute("current-version-info", sysVersion);

            ApiResult apiResult = new ApiResult();

            apiResult.setCode(408);
            apiResult.setData(sysVersion);
            apiResult.setMessage("版本参数错误");

            httpServletResponse.setContentType("application/json");
            httpServletResponse.setCharacterEncoding("utf-8");
            httpServletResponse.getWriter().write(JSON.toJSONString(apiResult));

            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private boolean isNoneVersion(String uri) {

        boolean result = false;
        if (parameters.getNoneSecurityPath() != null) {
            for (String pattern : parameters.getNoneSecurityPath()) {
                if (matcher.match(pattern, uri)) {
                    result = true;
                    break;
                }
            }
        }

        return result;
    }
}
